stl容器使用中的经验(十一)

您所在的位置:网站首页 stl list容器 stl容器使用中的经验(十一)

stl容器使用中的经验(十一)

2023-09-04 09:53| 来源: 网络整理| 查看: 265

我们首先看个例子。

#include #include #include #include using namespace std; class Widget { public: Widget(int a) : m_a(a) { if(a % 2 == 0) { m_isMeasured = true; } } bool isMeasured() { return m_isMeasured; } private: int m_a {0}; bool m_isMeasured {false}; }; int main() { typedef vector WidgetVec; typedef vector::iterator WidgetIter; WidgetVec v; for(int index = 0; index cout delete p; p = NULL; } }

然后通过for_each区间函数遍历容器,对容器进行指针析构。

for_each(v.begin(), v.end(), clenWidget);

之后再针对已经析构了需要删除元素的容器进行元素的删除,现在的删除就能够正常的使用erase-remove的用法。

v.erase(remove(v.begin(), v.end(), static_cast(NULL)), v.end());

但是如果容器中存的不是普通指针,而是具有引用计数功能的智能指针,也就不用考虑remove造成的困难,而可以直接使用erase-remove习惯用法。

typedef shared_ptr WidgetSptr; vector v; v.push_back(WidgetSptr(new Widget)); ... v.erase(remove_if(v.begin(), v.end(), not1(mem_fun(&Widget::isMeasured))), v.end());

主要是因为编译器会将智能指针隐式的转换为其内置指针Widget*。容器中存放的是智能指针,但是成员函数isMeasured必须通过内置指针才能调用。

对存储指针的容器在使用remove系列函数时要注意内存泄漏,可以使用有引用计数的智能指针代替,或者在调用remove函数之前,对需要删除的指针进行内存析构并置为0.



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3